<template>
  <div class="back-ground">
    <div class="login-container" style="border-radius: 10px; box-shadow: 0 0 10px rgba(0,0,0,0.2)">
      <div style="display: flex; flex-wrap: wrap; justify-content: center;">
        <div id="left-side">
          <div id="title"
            style="font-size: 30px; font-weight: bold; color: #333; margin-bottom: 20px;margin-top: 65px;padding-left: 35px">
            任务管理系统
          </div>
          <div style="flex: 1; display: flex; justify-content: center;">
            <img src="../assets/images/login.jpg" alt="登录图片" class="login-image" />
          </div>
        </div>
        <div class="login-box">
          <div style="padding: 20px; background-color: #ffffff; margin-left: auto; margin-right: auto;">
            <el-form ref="formRef" :model="data.form" :rules="data.rules" class="login-form">
              <div class="form-header">
                登录 LOGIN
              </div>
              <el-form-item prop="username">
                <el-input size="large" v-model="data.form.username" placeholder="请输入用户名或邮箱" prefix-icon="User"
                  class="input-field"></el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input show-password size="large" v-model="data.form.password" placeholder="请输入密码" prefix-icon="Lock"
                  class="input-field"></el-input>
              </el-form-item>
              <el-form-item prop="captcha">
                <div class="role-control" style="display: flex; align-items: center;">
                  <el-input size="large" v-model="data.form.captcha" placeholder="请输入验证码" style="width: 200px;"
                    class="input-field">
                  </el-input>
                  <div class="captcha-box" @click="refreshCaptcha" v-html="captchaText"></div>
                </div>
              </el-form-item>
              <el-form-item prop="role">
                <el-radio-group v-model="data.form.role" class="role-select">
                  <el-radio :value="user" :label="'user'">普通用户</el-radio>
                  <el-radio :value="admin" :label="'admin'">系统管理员</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-button @click="submitLogin" type="primary" size="large" class="submit-btn">登录</el-button>
              <div class="footer-links">
                <router-link to="/register" class="footer-link">没有账号？去注册</router-link>
              </div>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, onUnmounted } from "vue";
// import { login } from "@/api";
import { useLoginStore } from "@/store/login";

import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { login } from "@/api";

const router = useRouter();
const loginStore = useLoginStore();

const captchaText = ref('');
const currentCaptcha = ref('');
const formRef = ref(null);

const data = reactive({
  form: {
    username: '',
    password: '',
    captcha: '',
    role: 'user',
  },
  rules: {
    username: [
      { required: true, message: '请输入账号', trigger: 'blur' },
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 5, message: '密码最少5位', trigger: 'blur' },
    ],
    captcha: [
      { required: true, message: '请输入验证码', trigger: 'blur' },
    ],
    role: [
      { required: true, message: '请选择登录身份', trigger: 'change' },
    ],
  }
});

// 生成随机验证码
const generateCaptcha = () => {
  const characters = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789';
  let result = '';
  for (let i = 0; i < 4; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  currentCaptcha.value = result;
  console.log('Generated captcha:', result);

  captchaText.value = result.split('').map(char => {
    const color = `rgb(${Math.random() * 150 + 50}, ${Math.random() * 150 + 50}, ${Math.random() * 150 + 50})`;
    const rotate = Math.random() * 30 - 15;
    return `<span style="color: ${color}; display: inline-block; transform: rotate(${rotate}deg);">${char}</span>`;
  }).join('');
  console.log('Captcha HTML:', captchaText.value);
};

// 刷新验证码
const refreshCaptcha = () => {
  generateCaptcha();
};

// 在组件挂载时生成验证码
onMounted(() => {
  generateCaptcha();
  // loginStore.login(JSON.stringify({username:3,password:3,role:0,name:"",email:""}))
});

const submitLogin = () => {
  formRef.value.validate((valid) => {
    if (!valid) {
      return false;
    }

    if (data.form.captcha.toLowerCase() !== currentCaptcha.value.toLowerCase()) {
      ElMessage.error('验证码错误');
      generateCaptcha();
      data.form.captcha = '';
      return;
    }

    // 构建登录请求参数
    const loginParams = {
      username: data.form.username.trim(),
      password: data.form.password
    };

    login(loginParams)
      .then((res) => {
        console.log('登录响应:', res.data);

        if (res.data.code === 200) {
          const userRole = res.data.data.roleName;

          loginStore.setLoginInfo({
            token: res.data.data.jwtToken,
            userInfo: res.data,
            role: userRole
          });
          console.log('后端返回的角色:', userRole);
          if (data.form.role != userRole) {
            ElMessage.error("该账号不是当前角色！");
          } else {
            ElMessage.success('登录成功');
            if (userRole === 'admin' || userRole === 'ADMIN') {
              router.push('/reportManagement');
            } else {
              router.push('/userHome');
            }
          }

        } else {
          ElMessage.error(res.message || '登录失败');
          generateCaptcha();
          data.form.captcha = '';
        }
      })
      .catch((error) => {
        ElMessage.error('登录失败，请稍后重试');
        generateCaptcha();
        data.form.captcha = '';
      });
  });
};

// 在组件卸载时清除验证码相关数据
onUnmounted(() => {
  captchaText.value = '';
  currentCaptcha.value = '';
});
</script>

<style scoped>
.back-ground {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(to right, #ffffff, #ffffff);
  /* 渐变色背景 */
}

.login-container {
  display: flex;
  align-items: center;
  overflow: hidden;
  justify-content: center;
  background-color: white;
  border-radius: 10px;
}

.login-image {
  width: 95%;
  height: auto;
  max-height: 60%;
  object-fit: contain;
}

.login-box {
  width: 430px;
  max-width: 100%;
  margin: 0 auto;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 20px;
  box-shadow: 0 4px 8px rgba(255, 255, 255, 0.1);
  /* 增加阴影 */
  border-radius: 10px;
  /* 增加圆角 */
}

.login-form {
  width: auto;
  height: auto;
  margin-top: 15px;
  padding: 10px;
  box-sizing: border-box;
}

.form-header {
  font-size: 24px;
  text-align: center;
  color: #1e1e7c;
  font-weight: bold;
  margin-bottom: 20px;
}

.input-field {
  border: 0;
  width: 100%;
  font-size: 15px;
  color: #fff;
  background: transparent;
  border-bottom: 2px solid #fff;
  padding: 5px 10px;
  outline: none;
  margin-top: 10px;
}

.submit-btn {
  width: 100%;
  margin-top: 10px;
  font-size: 15px;
  letter-spacing: 2px;
  border-radius: 10px;
  border: 0;
  color: #fff;
  background-image: linear-gradient(to right, #33a2fd, #1e7dc5);
}

.footer-links {
  display: flex;
  justify-content: center;
  font-size: 13px;
  color: #0066bc;
  margin-top: 10px;
}

.footer-link {
  color: #4B6DF8;
  font-weight: 600;
  text-decoration: none;
}

@media (max-width: 825px) {
  .login-container {
    flex-direction: column;
  }

  .login-image {
    width: 250px;
    height: 250px;
    max-height: none;
  }

  .login-box {
    width: 90%;
    height: auto;
    margin-top: 20px;
  }

  .form-header {
    font-size: 20px;
  }

  .input-field {
    margin: 0;
  }

  .submit-btn {
    font-size: 14px;
  }

  .footer-links {
    flex-direction: column;
    align-items: center;
  }

  .footer-link {
    margin: 5px 0;
  }
}

.captcha-image {
  cursor: pointer;
  margin-right: 10px;
}

.captcha-box {
  margin-left: 10px;
  padding: 5px 10px;
  background: #f0f2f5;
  border-radius: 4px;
  cursor: pointer;
  user-select: none;
  font-size: 20px;
  font-family: 'Arial', sans-serif;
  letter-spacing: 3px;
  display: flex;
  align-items: center;
  min-width: 100px;
  height: 40px;
  justify-content: center;
}

.role-control {
  display: flex;
  align-items: center;
}

.role-select {
  width: 100%;
  margin-top: 10px;
  display: flex;
  justify-content: space-around;
}

.role-select :deep(.el-radio__label) {
  color: #606266;
  font-size: 14px;
}

.role-select :deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #409EFF;
}
</style>
